from django.shortcuts import render
from django.views import View
from PMSP.utils.my_category import get_category
from goods.models import SKU,GoodsCategory
from django.core.paginator import Paginator
from django import http
from datetime import datetime
from goods.models import CategoryVisitCount
import json
from django_redis import get_redis_connection

# 1,商品列表页面获取
class SKUListView(View):
    def get(self,request,category_id,page_num):

        # 0，获取排序选项
        sort = request.GET.get("sort","default")

        if sort == "price":
            sort_field = "-price"
        elif sort == "hot":
            sort_field = "-sales"
        else:
            sort_field = "-create_time"

        #  1,获取分类
        categories = get_category()

        # 2,查询sku商品,分页
        skus = SKU.objects.filter(category_id=category_id).order_by(sort_field)
        paginate = Paginator(skus,2)
        page = paginate.page(page_num) # page.number获取当前页，page.object_list获取当前页对象

        # 3,获取三级分类名称
        category = GoodsCategory.objects.get(id=category_id)

        # 4,携带数据渲染页面
        context = {
            "categories":categories,
            "skus":page.object_list,
            "current_page":page.number,
            "total_page":paginate.num_pages,
            "category":category,
            "sort":sort
        }
        return render(request,template_name="list.html",context=context)

# 2,热销商品
class HotSKUListView(View):
    def get(self,request,category_id):
        # 1，根据销量查询热门商品
        skus = SKU.objects.filter(category_id=category_id).order_by("-sales")[:3]

        # 2,将对象列表转换成字典列表
        sku_list = []
        for sku in skus:
            sku_dict = {
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price
            }
            sku_list.append(sku_dict)

        # 3，返回响应
        return http.JsonResponse({
            "code":0,
            "hot_sku_list":sku_list
        })

# 3,商品详情页
class SKUDetailView(View):
    def get(self,request,sku_id):

        categories = get_category()

        sku = SKU.objects.get(id=sku_id)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        context = {
            "sku":sku,
            "categories":categories,
            "category":sku.category,
            'specs': goods_specs,
        }
        return render(request,template_name='detail.html',context=context)

# 4,商品分类访问量统计
class CategoryVisitCountView(View):
    def post(self,request,category_id):
        #1,获取当天的日期
        today =  datetime.today()

        # 2,获取当前的分类访问量对象
        try:
            category_visit = CategoryVisitCount.objects.get(category_id=category_id,date=today)
        except Exception as e:
            category_visit = CategoryVisitCount(date=today,category_id=category_id)

        # 3,设置数量并入库
        category_visit.count += 1
        category_visit.save()

        # 4,返回响应
        return http.JsonResponse({"code":0})

# 5,浏览记录的保存
class SKUBrowserHistoryView(View):
    def post(self,request):
        # 1,获取参数
        dict_data =  json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")

        # 2,校验参数
        if not sku_id:
            return http.JsonResponse({"code":4000})

        # 3,数据去重
        redis_conn = get_redis_connection("history")
        redis_conn.lrem(f"history_{request.user.id}",0,sku_id)

        # 4,数据入库 lpush key value1 value2 value3
        redis_conn.lpush(f"history_{request.user.id}",sku_id)

        # 5,安全处理（保证只存5条）
        redis_conn.ltrim(f"history_{request.user.id}",0,4)

        # 6,返回响应
        return http.JsonResponse({"code":0})

    def get(self,request):
        #1,获取浏览记录
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange(f"history_{request.user.id}",0,4)

        #2,数据拼接处理
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id":sku.id,
                "name":sku.name,
                "price":sku.price,
                "default_image_url":sku.default_image_url.url,
            }
            sku_list.append(sku_dict)

        #3,返回响应
        return http.JsonResponse({"skus":sku_list,"code":0})